package org.jeecg.modules.demo.mthet.controller;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.mthet.entity.MtHet;
import org.jeecg.modules.demo.mthet.entity.VEcpHetinfo;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.demo.mthet.service.IMtHetService;
import org.jeecg.modules.demo.mthet.service.IVEcpHetinfoService;
import org.jeecg.modules.demo.mthetcar.entity.MtHetCar;
import org.jeecg.modules.demo.mthetcar.service.IMtHetCarService;
import org.jeecg.modules.demo.mthetkz.entity.MtHetkz;
import org.jeecg.modules.demo.mthetkz.service.IMtHetkzService;
import org.jeecg.modules.demo.mttldanjtk.entity.MtTlDanjtk;
import org.jeecg.modules.demo.mttldanjtk.service.IMtTlDanjtkService;
import org.jeecg.modules.demo.utils.DateUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: mt_het
 * @Author: jeecg-boot
 * @Date:   2025-04-30
 * @Version: V1.0
 */
@Api(tags="mt_het")
@RestController
@RequestMapping("/mtHet")
@Slf4j
public class MtHetController extends JeecgController<MtHet, IMtHetService> {
	@Autowired
	private IMtHetService mtHetService;
	@Autowired
	private IVEcpHetinfoService ecpHetinfoService;
	@Autowired
	private IMtHetkzService mtHetkzService;
	@Autowired
	private IMtTlDanjtkService mtTlDanjtkService;
	@Autowired
	private IMtHetCarService mtHetCarService;




	 @ApiOperation(value="v_ecp_hetinfo-分页列表查询", notes="v_ecp_hetinfo-分页列表查询")
	 @GetMapping(value = "/list")
	 public Result<IPage<VEcpHetinfo>> queryPageList(VEcpHetinfo vEcpHetinfo,
													 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
													 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
													 HttpServletRequest req,String dongzbm) {
		 QueryWrapper<VEcpHetinfo> queryWrapper = QueryGenerator.initQueryWrapper(vEcpHetinfo, req.getParameterMap());
		 if(dongzbm != null && !dongzbm.equals("")){
			 queryWrapper.eq("dongzbm",dongzbm);
		 }
		 Page<VEcpHetinfo> page = new Page<VEcpHetinfo>(pageNo, pageSize);
		 IPage<VEcpHetinfo> pageList = ecpHetinfoService.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }



	/**
	 *   添加
	 *
	 * @param mtHet
	 * @return
	 */
	@AutoLog(value = "mt_het-添加")
	@ApiOperation(value="mt_het-添加", notes="mt_het-添加")
	//@RequiresPermissions("mthet:mt_het:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody MtHet mtHet) {
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if(sysUser == null){
			return Result.error("用户已失效，请重新登录！");
		}

		String hetid = "0";
		String id = mtHetService.genrateHetId("MT_HET");
		String hetbh = mtHetService.getYaoYHetbh("1","T");
		MtHet mtHet1 = new MtHet();
		mtHet1.setHetbh(hetbh);
		mtHet1.setHetid(String.valueOf(Long.parseLong(id)));
		mtHet1.setChumdwbm(mtHet.getChumrssdwbm());
		mtHet1.setChumdwmc(mtHet.getChumrssdwmc());
		mtHet1.setChumdwjsrbm(mtHet.getChumrssdwbm());
		mtHet1.setChumdwjsrmc(mtHet.getChumrssdwmc());
		mtHet1.setChumrssdwbm(mtHet.getChumrssdwbm());
		mtHet1.setChumrssdwmc(mtHet.getChumrssdwmc());

		mtHet1.setMaisdwbm(mtHet.getMaisrssdwbm());
		mtHet1.setMaisdwmc(mtHet.getMaisrssdwmc());
		mtHet1.setMaisdwjsrbm(mtHet.getMaisrssdwbm());
		mtHet1.setMaisdwjsrmc(mtHet.getMaisrssdwmc());
		mtHet1.setMaisrssdwbm(mtHet.getMaisrssdwbm());
		mtHet1.setMaisrssdwmc(mtHet.getMaisrssdwmc());
		mtHet1.setHetlrbh(mtHet.getHetlrbh());
		mtHet1.setAttachment(mtHet.getAttachment());
		if(mtHet.getPosttype() != null){
			mtHet1.setHettype(mtHet.getPosttype());
		}
		//mtHet1.setHettype(mtHet.getHettype());
		mtHet1.setPlatenumber(mtHet.getPlatenumber());
		mtHet1.setTianshu(String.valueOf(Double.parseDouble(mtHet.getTianshu())));
		mtHet1.setJiage(mtHet.getJiage());
		mtHet1.setShul(mtHet.getShul());

		//mtHet.setHetid(id);
		mtHet1.setSysid(Integer.parseInt(id)+1);
		String gxsj = DateUtil.formatLongNow();
		String qdsj = DateUtil.fomatShortNow();
		mtHet1.setGengxsj(gxsj);
		mtHet1.setQianysj(mtHet.getQianysj());
		//55属于直接录入的归档合同
		mtHet1.setDongzbm("55");
		mtHet1.setZhuangt("4");
		mtHet1.setCaozr(sysUser.getUsername());
		mtHet1.setDongzlx("1");
		mtHet1.setChumrlx("1");
		mtHet1.setNianf(DateUtil.fomatYearNow());
		mtHet1.setYouxqxkssj(mtHet.getYouxqxkssj());
		mtHet1.setYouxqxjssj(mtHet.getYouxqxjssj());
		mtHet1.setBrandmodel(mtHet.getBrandmodel());
		mtHet1.setNianf(DateUtil.fomatYearNow());
		//mtHet1.setYouxqxkssj(DateUtil.fomatShortNow());
		//mtHet1.setYouxqxjssj(DateUtil.fomatYearNow() + "-12-31");

		MtHetkz hetkz = new MtHetkz();
		hetkz.setGengxsj(gxsj);
		Double jiage = mtHet.getJiage();
		if(jiage != null){
			hetkz.setJiag(BigDecimal.valueOf(jiage));
			mtHet1.setJiage(jiage);
		}

		String shul = mtHet.getShul();
		if(shul != null && !shul.equals("")){
			hetkz.setShul(BigDecimal.valueOf(Double.parseDouble(shul)));
			hetkz.setHej(BigDecimal.valueOf(Double.parseDouble(shul)));
		}
		hetkz.setHetid(id);
		hetkz.setShouhdwbm(mtHet.getMaisrssdwbm());
		hetkz.setShouhdwmc(mtHet.getMaisrssdwmc());
		Double total = 0.0;
		try{
			if(mtHet.getCarlist() != null) {
				JSONArray jsonArray = JSON.parseArray(mtHet.getCarlist());
				int size = jsonArray.size();
				for (int i = 0; i < size; i++) {

					MtHetCar mtHetCar = new MtHetCar();

					mtHetCar.setId(Integer.parseInt(mtHetCarService.genrateHetCarId("mt_het_car")));

					JSONObject jsonObject = jsonArray.getJSONObject(i);

					if (jsonObject.get("brandmodel") != null) {
						mtHetCar.setBrandmodel(jsonObject.getString("brandmodel"));
					}
//					if (jsonObject.get("hetid") != null) {
//						mtHetCar.setHetid(jsonObject.getInteger("hetid"));
//					}
					mtHetCar.setHetid(Integer.parseInt(id));
					if (jsonObject.get("platenumber") != null) {
						mtHetCar.setPlatenumber(jsonObject.getString("platenumber"));
					}
					if (jsonObject.get("rentprice") != null) {
						mtHetCar.setRentprice(jsonObject.getString("rentprice"));
						total = total + Double.parseDouble(mtHetCar.getRentprice());
					}
					if (jsonObject.get("rentstartdate") != null) {
						mtHetCar.setRentstartdate(jsonObject.getString("rentstartdate"));
					}
					if (jsonObject.get("rententdate") != null) {
						mtHetCar.setRententdate(jsonObject.getString("rententdate"));
					}
					if (jsonObject.get("remark") != null) {
						mtHetCar.setRemark(jsonObject.getString("remark"));
					}

					mtHetCarService.save(mtHetCar);
				}
			}
			mtHet1.setTotal(total.toString());
			mtHetService.save(mtHet1);
			mtHetkzService.save(hetkz);
		}catch (Exception e){
			e.printStackTrace();
			return Result.error("保存失败！");
		}

		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param mtHet
	 * @return
	 */
	@AutoLog(value = "mt_het-编辑")
	@ApiOperation(value="mt_het-编辑", notes="mt_het-编辑")
	//@RequiresPermissions("mthet:mt_het:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody MtHet mtHet) {
		if(mtHet.getPosttype() != null){
			mtHet.setHettype(mtHet.getPosttype());
		}
		try{
			if(mtHet.getCarlist() != null) {

				if(mtHet.getHetid() != null){
					QueryWrapper<MtHetCar> queryWrapper = new QueryWrapper<MtHetCar>();
					this.mtHetCarService.remove(queryWrapper.eq("HETID",mtHet.getHetid()));
				}

				JSONArray jsonArray = JSON.parseArray(mtHet.getCarlist());
				int size = jsonArray.size();
				for (int i = 0; i < size; i++) {

					MtHetCar mtHetCar = new MtHetCar();

					mtHetCar.setId(Integer.parseInt(mtHetCarService.genrateHetCarId("mt_het_car")));

					JSONObject jsonObject = jsonArray.getJSONObject(i);

					if (jsonObject.get("brandmodel") != null) {
						mtHetCar.setBrandmodel(jsonObject.getString("brandmodel"));
					}
					if (jsonObject.get("hetid") != null) {
						mtHetCar.setHetid(jsonObject.getInteger("hetid"));
					}
					if (jsonObject.get("platenumber") != null) {
						mtHetCar.setPlatenumber(jsonObject.getString("platenumber"));
					}
					if (jsonObject.get("rentprice") != null) {
						mtHetCar.setRentprice(jsonObject.getString("rentprice"));
					}
					if (jsonObject.get("rentstartdate") != null) {
						mtHetCar.setRentstartdate(jsonObject.getString("rentstartdate"));
					}
					if (jsonObject.get("rententdate") != null) {
						mtHetCar.setRententdate(jsonObject.getString("rententdate"));
					}
					if (jsonObject.get("remark") != null) {
						mtHetCar.setRemark(jsonObject.getString("remark"));
					}

					mtHetCarService.save(mtHetCar);
				}
				mtHetService.updateById(mtHet);
			}
		}catch(Exception e){
			e.printStackTrace();
			return Result.error("归档失败，请重试！");
		}
		return Result.OK("归档成功!");
	}


	 @AutoLog(value = "mt_het-委托合同编辑")
	 @ApiOperation(value="mt_het-委托合同编辑", notes="mt_het-编辑")
	 //@RequiresPermissions("mthet:mt_het:edit")
	 @RequestMapping(value = "/editwt", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> editwt(@RequestBody MtHet mtHet) {
		mtHetService.updateById(mtHet);
		 return Result.OK("归档成功!");
	 }


	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "mt_het-通过id删除")
	@ApiOperation(value="mt_het-通过id删除", notes="mt_het-通过id删除")
	//@RequiresPermissions("mthet:mt_het:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		MtHet mthet = this.mtHetService.getById(id);
		if(mthet.getHetid() != null){
			QueryWrapper<MtHetCar> queryWrapper = new QueryWrapper<MtHetCar>();
			this.mtHetCarService.remove(queryWrapper.eq("HETID",mthet.getHetid()));
		}
		mtHetService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "mt_het-批量删除")
	@ApiOperation(value="mt_het-批量删除", notes="mt_het-批量删除")
	//@RequiresPermissions("mthet:mt_het:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.mtHetService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "mt_het-通过id查询")
	@ApiOperation(value="mt_het-通过id查询", notes="mt_het-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<MtHet> queryById(@RequestParam(name="id",required=true) String id) {
		MtHet mtHet = mtHetService.getById(id);
		MtHetkz mtHetkz = mtHetkzService.findhetkzgetbyhetId(mtHet.getHetid());
		mtHet.setJiage(mtHetkz.getJiag().doubleValue());
		if(mtHet==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(mtHet);
	}



    /**
    * 导出excel
    *
    * @param request
    * @param mtHet
    */
    @RequiresPermissions("mthet:mt_het:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MtHet mtHet) {
        return super.exportXls(request, mtHet, MtHet.class, "mt_het");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("mthet:mt_het:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MtHet.class);
    }



}
